/*
 * @(#)Template.java 1.0 2000/12/28
 * 
 * Copyright 2000 Thomas Barnekow. All Rights Reserved.
 * 
 * This software is the proprietary information of Thomas Barnekow. Use is
 * subject to license terms.
 */

package jessx.provider;

import java.util.*;

import jess.*;

import tb.provider.*;
import tb.util.*;

/**
 * A {@link CompoundMetaObject}representing a {@link Deftemplate}.
 * 
 * @author Thomas Barnekow
 * @version 1.0
 */
public class Template
	extends AbstractCompoundMetaObject
	implements NamedObject {

	public static final String DELIMITER = "-";

	private Rete m_engine;

	private Template m_parent;
	private String m_comment;

	public Template(QualifiedName name, Rete engine) {
		super(name);
		m_engine = engine;
	}

	public Template(
		QualifiedName name,
		CompoundMetaObject container,
		Rete engine) {
		super(name, container);
		m_engine = engine;
	}

	protected Collection createElementCollection() throws Exception {
		return new ArrayList();
	}

	public QualifiedName getQualifiedName() {
		return (QualifiedName) getId();
	}

	public void setParent(Template value) {
		m_parent = value;
	}

	public Template getParent() {
		return m_parent;
	}

	public void setComment(String value) {
		m_comment = value;
	}

	public String getComment() {
		return m_comment;
	}

	public boolean addSlot(String name, Value defaultValue, String typeName)
		throws Exception {
		Slot slot = new Slot(name, this);
		slot.setDefaultValue(defaultValue);
		slot.setTypeName(typeName);
		return add(slot);
	}

	/**
	 * Create a {@link jess.Deftemplate}.
	 */
	public Object getDeclaration() {
		String name = getQualifiedName().toString(DELIMITER);
		Deftemplate dt = null;

		try {
			dt =
				(m_parent != null)
					? new Deftemplate(
						name,
						m_comment,
						(Deftemplate) m_parent.getDeclaration(),
						m_engine)
					: new Deftemplate(name, m_comment, m_engine);

			Iterator slots = iterator();
			while (slots.hasNext()) {
				Slot slot = (Slot) slots.next();
				dt.addSlot(
					slot.getName(),
					slot.getDefaultValue(),
					slot.getTypeName());
			}
		} catch (JessException ex) {
			throw new RuntimeException(ex.toString());
		}

		return dt;
	}

	public String toString() {
		StringBuffer buffer = new StringBuffer(64 + 128 * size());

		buffer.append("(deftemplate ").append(
			getQualifiedName().toString(DELIMITER));
		Iterator iterator = iterator();
		while (iterator.hasNext()) {
			buffer.append("\n    ").append(iterator.next());
		}
		buffer.append(')');

		return buffer.toString();
	}
}